//
//  StatusListViewModel.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/16.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage


class StatusListViewModel: NSObject {
    //MARK: 加载微博首页数据
    class func loadData(since_id since_id: Int, max_id: Int, finished:(array: [Status]?) -> ()) {
        //let AFN = AFHTTPSessionManager()
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showErrorWithStatus("你未登陆")
            return
        }
        var parameters = ["access_token": token]
        
        // 添加 since_id 对应键值对
        if since_id > 0 {
            // \(since_id) 转换成字符串
            parameters["since_id"] = "\(since_id)"
        }
        //添加 max_id 对应的键值对
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {
                finished(array: nil)
                return
            }
            
            if let array  = result! ["statuses"] as? [[String: AnyObject]]{
                //定义一个数组 数组里面的对象是Status 类型的
                var list = [Status]()
                for item in array{
                    //字典转模型
                    let s = Status(dict: item)
                    //条件微博对象
                    list.append(s)
                }
                //完成回调
                StatusListViewModel.cacheStausImage(list, finished: finished)
            }
        }
    }
    
    private class func cacheStausImage(array: [Status],finished: (array: [Status]?) -> ()){
        // 缓存单张图片
        if array.count == 0{
            finished(array: array)
            return
        }
        
        let group = dispatch_group_create()
        
        //遍历模型数组
        for s in array{
            if let imageurls = s.pictureURLs{
                
                //如果不是单张图片
                if imageurls.count != 1{
                    continue
                }
                //一定是单张图片
                for url in imageurls{
                    //开始下载图片
                    //异步加载图片的开始
                    //向群组中添加异步任务
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("单张图片下载完成")
                        //异步任务离开群组
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //在主线程完成回调
            print("所有异步图片下载完成")
            finished(array: array)
        }
    }
}
